import { Application, Router } from "https://deno.land/x/oak@v17.1.1/mod.ts";
import { Session } from "https://deno.land/x/oak_sessions@v4.1.11/mod.ts";
import { send } from "https://deno.land/x/oak@v17.1.1/send.ts";
import { getUser, handleError, handleResult } from "../lib/utils.ts";
import { findOne } from "../db/index.ts";
import { findMany } from "../db/index.ts";
export type AppState = {
  session: Session
}

export const router = new Router<AppState>();
router.get("/", async (context) => {
  await send(context, "index.html");
});

router.get("/viewer", async (context) => {
  const user = await getUser(context)
  handleResult(context, user)
})
router.post("/login", async (context) => {
  const body = context.request.body
  const { account, password } = await body.json()
  const user = await findOne<any>("SELECT * FROM users WHERE account = $1", [account])
  if (!user) {
    return handleError(context, "account not exist")
  }
  if (user.password !== password) {
    return handleError(context, "password error")
  }
  context.state!.session.set("user_id", user.id)
  handleResult(context, user)
})
router.post("/register", async (context) => {
  const body = context.request.body
  const { account, password } = await body.json()
  await findOne("INSERT INTO users (account, password) VALUES ($1, $2)", [account, password])
  handleResult(context, "register success")
  context.state!.session.set("user_id", 1)
})
router.get("/links", async (context) => {
  const query = context.request.url.searchParams
  const start_id = parseInt(query.get("start_id") || "0");
  const links = await findMany<any[]>("SELECT * FROM sys_link WHERE id < $1 ORDER BY id DESC LIMIT 5", [start_id])
  handleResult(context, links)
})
router.put("/link", async (context) => {
  const user = await getUser(context)
  if (!user) return handleError(context, "not login")
  const body = context.request.body
  const { title, description, link } = await body.json()
  await findOne("INSERT INTO sys_link (title, link,description,user_id) VALUES ($1, $2)", [title, link, description, user.id])
  handleResult(context, "success")
})
router.delete("/link", async (context) => {
  const user = await getUser(context)
  if (!user) return handleError(context, "not login")
  const body = context.request.body
  const { id } = await body.json()
  await findOne("DELETE FROM sys_link WHERE id = $1", [id])
  handleResult(context, "success")
})
router.patch("/link", async (context) => {
  const user = await getUser(context)
  if (!user) return handleError(context, "not login")
  const body = context.request.body
  const { id, title, description } = await body.json()
  await findOne("UPDATE sys_link SET title=$1,description=$2 WHERE id = $3", [title, description, id])
  handleResult(context, "success")
})
router.patch("/link/like", async (context) => {
  const user = await getUser(context)
  if (!user) return handleError(context, "not login")
  const body = context.request.body
  const { id, score } = await body.json()
  await findOne("INSERT INTO user_on_link (sys_user_id,sys_link_id,score) VALUES ($1,$2,$3)", [user.id, id, score])
  await findOne("UPDATE sys_link SET score = score + $1 AND total = total + 1 WHERE id = $2", [score, id])
  handleResult(context, "success")
})

router.get("/folder", async (context) => {
  const user = await getUser(context)
  if (!user) return handleError(context, "not login")
  const query = context.request.url.searchParams
  const start_id = parseInt(query.get("start_id") || "0");
  let folder: any = await findOne("SELECT * FROM sys_folder WHERE user_id = $1", [user.id])
  if (!folder) {
    await findOne("INSERT INTO sys_folder (user_id) VALUES ($1)", [user.id])
    folder = await findOne("SELECT * FROM sys_folder WHERE user_id = $1", [user.id])
  }
  const link_on_folder = await findMany("SELECT * FROM link_on_folder WHERE folder_id = $1 AND id < $2 ORDER BY id DESC LIMIT 5", [folder.id, start_id])
  handleResult(context, link_on_folder)
})
router.post("/folder/detail", async (context) => {
  const user = await getUser(context)
  if (!user) return handleError(context, "not login")
  const body = context.request.body
  const { ids } = await body.json()

})




export const createApp = () => {
  const app = new Application<AppState>()

  app.addEventListener('error', (evt) => {
    console.log(evt.error, "error")
  })

  app.use(Session.initMiddleware())

  app.use(router.routes());
  app.use(router.allowedMethods());
  return app
}